/*
 * @Author: xiaxia
 * @Description: 
 * @Date: 2024-06-20 11:05:16
 * @LastEditTime: 2024-06-26 11:31:43
 * @FilePath: \project\src\store\modules\user.ts
 */
import {defineStore} from 'pinia'
import {constantaRoute} from '@/router/routes'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import type { loginForm, loginResponse, userPesponseData } from '@/api/user/type'
import type {UserState} from './types/type'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'

let useUserStore = defineStore('User', {
  state: ():UserState => {
    return {
      menuRoutes: constantaRoute,// 菜单路由
      token: GET_TOKEN(),
      username: '',
      avatar: ''
    }
  },
  actions: {
    // 用户登录
    async userLogin(data:loginForm){      
      const res:loginResponse = await reqLogin(data)
      if(res.code!=200) return Promise.reject(new Error(res.data))
      this.token = (res.data as string)
      SET_TOKEN((res.data as string))
    },
    // 获取用户信息
    async getUserInfo() {
      let res:userPesponseData = await reqUserInfo()
      if(res.code!=200) return Promise.reject('获取用户信息失败')
      this.username = res.data.name
      this.avatar = res.data.avatar
      return 'ok'
    },
    // 退出登录
    async userLogout() {
      let res:any = await reqLogout()
      if(res.code!=200) return Promise.reject(new Error(res.message))
      this.token = ''
      this.username = ''
      this.avatar = ''
      REMOVE_TOKEN()
      return 'ok'
    }
  },
  getters: {

  }
})

export default useUserStore